JavaScript Keyed Collections

Visualizing `Map`, `Set`, `WeakMap`, and `WeakSet`.

Map

A collection of key-value pairs where both keys and values can be of any data type. It maintains the insertion order of its elements and is iterable. Unlike plain objects, keys are not limited to strings or symbols.

const map = new Map();
map.set('name', 'Alice');
map.set(1, 'number key');

A `Map` is like a dictionary where you can use anything as a word (key) to look up a definition (value).


Set

A collection of unique values. It's like a list where every item can only appear once. Sets are useful for removing duplicates from an array or checking for the presence of an item.

const set = new Set();
set.add(1);
set.add(1); // Ignored
set.add('hello');

A `Set` is a unique-items-only club. If an item is already a member, it won't be added again.


WeakMap

A collection of key-value pairs where the keys must be objects and are held "weakly." If the only remaining reference to a key object is in the `WeakMap`, the object and its value will be garbage-collected.

const weakMap = new WeakMap();
let obj = {};
weakMap.set(obj, 'data');
// When 'obj' is no longer referenced, weakMap entry is removed.

A `WeakMap` is a private, non-permanent storage locker. It only holds onto things as long as they are needed elsewhere in your code.

Important: Weak collections cannot be iterated or cleared. They are designed for internal use to prevent memory leaks.


WeakSet

A collection of unique objects where references are held "weakly." It's similar to `WeakMap` but only stores values (not key-value pairs), and those values must be objects.

const weakSet = new WeakSet();
let obj = {};
weakSet.add(obj);
// When 'obj' is no longer referenced, weakSet entry is removed.

A `WeakSet` is a list of objects that don't need to be kept around if the objects are no longer in use.

Important: Like `WeakMap`, a `WeakSet` is not iterable and cannot be cleared.